<?php

class SmsSendController extends Controller
{

	/**
     * 过滤器
	 * @return 返回值是一个存放过滤器的数组
	 */
	public function filters()
	{
		return array(
            'accessAuth',//自定义授权方式
			//'accessControl', //默认授权方式
			'postOnly + delete',//删除操作只支持post请求
		);
	}
    /**
     * 自定义权限验证规则
     * @param type $filterChain
     * @throws CHttpException
     */
    public function filterAccessAuth($filterChain) {  
        if(Yii::app()->user->getIsGuest()) {  
            echo '<script>top.location.href="'.Yii::app()->user->returnUrl.'";</script>';
            exit;
        } else if(!Yii::app()->user->getIsGuest() && !in_array($this->getAction()->getId(), $this->authlessActions())){
            throw new CHttpException(403,'无权访问此页面');
        }
        $filterChain->run();  
    }  
    /**
     * 页面白名单
     * @return type
     */
    public function authlessActions() {  
        return array(
            'index','admin','view','create','update','delete','preview','batchCreate'
		); 
    }

	/**
	 * 查看页面
	 * @param integer $id
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * 添加页面
	 * 如果添加成功，跳转到查看页面
	 */
	public function actionCreate()
	{
		$model=new SmsSend;

		//如果前台开启ajax则取消此注释
		//$this->performAjaxValidation($model);

		if(isset($_POST['SmsSend']))
		{
			$model->attributes=$_POST['SmsSend'];
                        $model->create_time=date('Y-m-d H:i:s',time());
                        $model->create_user=Yii::app()->user->username;
                        $model->is_float=1;
                        //获取发送信息内容
                        $sms_msg=Sms::model()->findByPk($model->sms_id);
                        if(!empty($sms_msg)){
                            $model->sms_content=$sms_msg->content;
                        }
                        Ccommon::smsYX($model->phone,Sms::model()->findByPk($model->sms_id)->content);
			if($model->save()){
                            Yii::app()->user->setFlash('success','操作成功！');
                            $this->redirect(array('SmsSend/admin'));
                        }
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * 修改页面
	 * 如果修改成功，跳转到查看页面
	 * @param integer $id 
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		//如果前台开启ajax则取消此注释
		//$this->performAjaxValidation($model);

		if(isset($_POST['SmsSend']))
		{

                        include_once(dirname(dirname(__FILE__)).'\extensions\PHPExcel\PHPExcel\IOFactory.php');  
                        $reader = PHPExcel_IOFactory::createReader('Excel2007'); // 读取 excel 文件
                        $PHPExcel = PHPExcel_IOFactory::load("1.xls");
                        $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表(编号从 0 开始)  
                        $highestRow = $sheet->getHighestRow(); // 取得总行数  
                        $highestColumn = $sheet->getHighestColumn(); // 取得总列数  
                     
			$model->attributes=$_POST['SmsSend'];
			if($model->save()){
//                            Yii::app()->user->setFlash('success','操作成功！');
//                            $this->redirect(array('SmsSend/admin'));
                               print_r($highestRow);
                        }
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * 删除功能
	 * 一般只接受post方式的异步提交
	 * @param integer $id 
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isAjaxRequest && isset($_POST['id'])){
            $id=$_POST['id'];
            //获取id数组批量删除
            $criteria= new CDbCriteria;
            $criteria->addInCondition('id', $id);
            $res=SmsSend::model()->deleteAll($criteria);
            //输出json结果
            echo CJSON::encode(array('result'=>$res));
        }else{
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        } 
	}

	/**
	 * 列表页
	 */
	public function actionAdmin()
	{
		$model=new SmsSend('search');
		$model->unsetAttributes();  //清空并初始化
		if(isset($_GET['SmsSend']))
			$model->attributes=$_GET['SmsSend'];

		$this->render('admin',array(
			'model'=>$model,
			'data'=>$model->search(),
		));
	}
        
        
        public function actionPreview()
        {
            $data=new Sms();
            if(!empty($_POST['smsid']))
                $data = Sms::model()->find('id=:id',array(':id'=>(int)$_POST['smsid']));
            else
                $data->content='';
                
            echo CJSON::encode(array(
                'content'=>$data->content,
               
            ));
        }

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return SmsSend the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=SmsSend::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param SmsSend $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='sms-send-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        //批量导入
        public function actionBatchCreate(){
            if(!empty($_POST['userfile'])){
                $path=$_POST['userfile'];
                $len=strlen($path);
//              $index=strpos($path,'/',2);
                $index=strpos($path,'/',4);
                $path=substr($path,$index+1,$len);
                include_once(dirname(dirname(__FILE__)).'/extensions/PHPExcel/PHPExcel/IOFactory.php');  
                $reader = PHPExcel_IOFactory::createReader('Excel2007'); // 读取 excel 文件
                $PHPExcel = PHPExcel_IOFactory::load($path);
                $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表(编号从 0 开始)  
                $highestRow = $sheet->getHighestRow(); // 取得总行数  
                $highestColumn  = $sheet->getHighestColumn(); // 取得总列数  
                $transaction = Yii::app()->db->beginTransaction(); //创建事务    
                for ($row = 2; $row <= $highestRow; $row++) {
                    $data = array();
                    for ($column = 0; $column <= 2; $column++)  {  
                        $val = $sheet->getCellByColumnAndRow($column, $row)->getValue(); 
                        $data[$column]=$val;  
                    }
                    $model = new SmsSend;
                    $model->unsetAttributes();
                    $model->sms_id=$data[0];
                    $model->username=$data[1];
                    $model->phone=$data[2];
                    $model->create_time=date('Y-m-d H:i:s',time());
                    $model->create_user=Yii::app()->user->username;
                    $model->is_float=1; 
                    //获取发送信息内容
                    $sms_msg=Sms::model()->findByPk($model->sms_id);
                    if(!empty($sms_msg)){
                        $model->sms_content=$sms_msg->content;
                    }
                    if($model->save()){
                        $send=Sms::model()->findByPk($model->sms_id);
                        if(!empty($send)){
                             Ccommon::smsYX($model->phone,$send->content);
                        }
                        
                    }
                   
                }
                $transaction->commit(); //提交事务
                Yii::app()->user->setFlash('success','操作成功！');
                $this->redirect(array('SmsSend/admin'));
            }  else {
                Yii::app()->user->setFlash('upload_error','请选择上传文件！');
                $this->redirect(array('SmsSend/create'));                    
            }
        }        
}
